<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
      th:replace="~{admin/layout/base :: html(~{::title}, ~{::content}, ~{::script})}">
<head>
    <title>居民管理 - 废物回收管理系统</title>
</head>
<body>
<th:block th:fragment="content">
    <div class="content-header">
        <div class="d-flex justify-content-between align-items-center">
            <h5 class="mb-0">居民管理</h5>
            <button type="button" class="btn btn-primary" onclick="showAddModal()">
                <i class='bx bx-plus'></i> 添加居民
            </button>
        </div>
    </div>

    <!-- 搜索栏 -->
    <div class="content-card mb-4">
        <div class="row">
            <div class="col-md-4">
                <div class="input-group">
                    <input type="text" class="form-control" id="searchInput" placeholder="输入用户名、手机号搜索">
                    <button class="btn btn-outline-secondary" type="button" onclick="searchResidents()">
                        <i class='bx bx-search'></i>
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- 居民列表 -->
    <div class="content-card">
        <div class="table-responsive">
            <table class="table">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>用户名</th>
                        <th>真实姓名</th>
                        <th>手机号</th>
                        <th>邮箱</th>
                        <th>地址</th>
                        <th>状态</th>
                        <th>注册时间</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody id="residentsList">
                    <!-- 数据将通过JavaScript动态加载 -->
                </tbody>
            </table>
        </div>
    </div>

    <!-- 添加/编辑居民模态框 -->
    <div class="modal fade" id="residentModal" tabindex="-1" role="dialog" aria-labelledby="modalTitle">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="modalTitle">添加居民</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="关闭"></button>
                </div>
                <div class="modal-body">
                    <form id="residentForm">
                        <input type="hidden" id="userId">
                        <div class="mb-3">
                            <label class="form-label" for="username">用户名</label>
                            <input type="text" class="form-control" id="username" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label" for="password">密码</label>
                            <input type="password" class="form-control" id="password" 
                                   placeholder="编辑时留空表示不修改密码">
                        </div>
                        <div class="mb-3">
                            <label class="form-label" for="realName">真实姓名</label>
                            <input type="text" class="form-control" id="realName">
                        </div>
                        <div class="mb-3">
                            <label class="form-label" for="phone">手机号</label>
                            <input type="tel" class="form-control" id="phone">
                        </div>
                        <div class="mb-3">
                            <label class="form-label" for="email">邮箱</label>
                            <input type="email" class="form-control" id="email">
                        </div>
                        <div class="mb-3">
                            <label class="form-label" for="address">地址</label>
                            <input type="text" class="form-control" id="address">
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" onclick="saveResident()">保存</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 在body结束标签前添加Bootstrap JS -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
</th:block>

<th:block th:fragment="script">
    <script th:inline="javascript">
    let residentModal;
    
    // 页面加载完成后执行
    document.addEventListener('DOMContentLoaded', function() {
        loadResidents();
        // 初始化模态框
        residentModal = new bootstrap.Modal(document.getElementById('residentModal'));
    });

    // 加载居民列表
    function loadResidents() {
        fetch('/admin/users/search?role=RESIDENT&keyword=')
            .then(response => {
                if (!response.ok) {
                    throw new Error('网络响应不正常');
                }
                return response.json();
            })
            .then(result => {
                if (result.code !== 200) {
                    throw new Error(result.message || '加载失败');
                }
                
                const data = result.data;
                const tbody = document.getElementById('residentsList');
                tbody.innerHTML = '';
                
                if (!Array.isArray(data)) {
                    console.error('返回数据格式不正确:', data);
                    throw new Error('数据格式不正确');
                }
                
                if (data.length === 0) {
                    tbody.innerHTML = '<tr><td colspan="9" class="text-center">暂无居民数据</td></tr>';
                    return;
                }
                
                data.forEach(resident => {
                    const tr = document.createElement('tr');
                    tr.innerHTML = `
                        <td>${resident.id}</td>
                        <td>${resident.username}</td>
                        <td>${resident.realName || '-'}</td>
                        <td>${resident.phone || '-'}</td>
                        <td>${resident.email || '-'}</td>
                        <td>${resident.address || '-'}</td>
                        <td>
                            <span class="badge ${resident.status === 1 ? 'bg-success' : 'bg-danger'}">
                                ${resident.status === 1 ? '正常' : '禁用'}
                            </span>
                        </td>
                        <td>${formatDate(resident.createTime)}</td>
                        <td>
                            <button class="btn btn-sm btn-info" onclick="editResident(${resident.id})">
                                编辑
                            </button>
                            <button class="btn btn-sm ${resident.status === 1 ? 'btn-warning' : 'btn-success'}"
                                    onclick="toggleStatus(${resident.id}, ${resident.status})">
                                ${resident.status === 1 ? '禁用' : '启用'}
                            </button>
                            <button class="btn btn-sm btn-danger" onclick="deleteResident(${resident.id})">
                                删除
                            </button>
                        </td>
                    `;
                    tbody.appendChild(tr);
                });
            })
            .catch(error => {
                console.error('加载居民列表失败:', error);
                const tbody = document.getElementById('residentsList');
                tbody.innerHTML = '<tr><td colspan="9" class="text-center text-danger">加载居民列表失败，请刷新页面重试</td></tr>';
            });
    }

    // 显示添加模态框
    function showAddModal() {
        document.getElementById('modalTitle').textContent = '添加居民';
        document.getElementById('residentForm').reset();
        document.getElementById('userId').value = '';
        if (!residentModal) {
            residentModal = new bootstrap.Modal(document.getElementById('residentModal'));
        }
        residentModal.show();
    }

    // 编辑居民
    function editResident(id) {
        fetch(`/admin/users/search?role=RESIDENT&keyword=&id=${id}`)
            .then(response => {
                if (!response.ok) {
                    throw new Error('获取数据失败');
                }
                return response.json();
            })
            .then(result => {
                if (result.code !== 200 || !result.data || !result.data.length) {
                    throw new Error(result.message || '获取数据失败');
                }
                const data = result.data[0];
                
                document.getElementById('modalTitle').textContent = '编辑居民';
                document.getElementById('userId').value = data.id;
                document.getElementById('username').value = data.username;
                document.getElementById('password').value = '';
                document.getElementById('realName').value = data.realName || '';
                document.getElementById('phone').value = data.phone || '';
                document.getElementById('email').value = data.email || '';
                document.getElementById('address').value = data.address || '';
                
                if (!residentModal) {
                    residentModal = new bootstrap.Modal(document.getElementById('residentModal'));
                }
                residentModal.show();
            })
            .catch(error => {
                console.error('获取居民信息失败:', error);
                alert('获取居民信息失败，请重试');
            });
    }

    // 保存居民信息
    function saveResident() {
        const userId = document.getElementById('userId').value;
        const data = {
            username: document.getElementById('username').value,
            password: document.getElementById('password').value,
            realName: document.getElementById('realName').value,
            phone: document.getElementById('phone').value,
            email: document.getElementById('email').value,
            address: document.getElementById('address').value,
            role: 'RESIDENT'
        };

        // 如果是编辑模式且密码为空，则不发送密码字段
        if (userId && !data.password) {
            delete data.password;
        }

        const url = userId ? `/admin/residents/${userId}` : '/admin/residents';
        const method = userId ? 'PUT' : 'POST';

        fetch(url, {
            method: method,
            headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/json'
            },
            body: JSON.stringify(data)
        })
        .then(response => {
            if (response.status === 200 || response.status === 204) {
                if (residentModal) {
                    residentModal.hide();
                }
                loadResidents();
                alert('保存成功');
                return;
            }
            
            // 尝试读取响应内容
            return response.text().then(text => {
                try {
                    const result = text ? JSON.parse(text) : {};
                    throw new Error(result.message || '保存失败');
                } catch (e) {
                    throw new Error(text || '保存失败');
                }
            });
        })
        .catch(error => {
            console.error('保存居民信息失败:', error);
            alert('保存居民信息失败: ' + error.message);
        });
    }

    // 切换居民状态
    function toggleStatus(id, currentStatus) {
        const newStatus = currentStatus === 1 ? 0 : 1;
        fetch(`/admin/users/${id}/status?status=${newStatus}`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/json'
            }
        })
        .then(response => {
            if (response.status === 200 || response.status === 204) {
                loadResidents();
                return;
            }
            
            // 尝试读取响应内容
            return response.text().then(text => {
                try {
                    const result = text ? JSON.parse(text) : {};
                    throw new Error(result.message || '更新状态失败');
                } catch (e) {
                    throw new Error(text || '更新状态失败');
                }
            });
        })
        .catch(error => {
            console.error('更新居民状态失败:', error);
            alert('更新状态失败: ' + error.message);
        });
    }

    // 删除居民
    function deleteResident(id) {
        if (!confirm('确定要删除这个居民吗？')) {
            return;
        }

        fetch(`/admin/residents/${id}`, {
            method: 'DELETE',
            headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/json'
            }
        })
        .then(response => {
            if (response.status === 200 || response.status === 204) {
                loadResidents();
                alert('删除成功');
                return;
            }
            
            // 尝试读取响应内容
            return response.text().then(text => {
                try {
                    const result = text ? JSON.parse(text) : {};
                    throw new Error(result.message || '删除失败');
                } catch (e) {
                    throw new Error(text || '删除失败');
                }
            });
        })
        .catch(error => {
            console.error('删除居民失败:', error);
            alert('删除失败: ' + error.message);
        });
    }

    // 搜索居民
    function searchResidents() {
        const keyword = document.getElementById('searchInput').value;
        fetch(`/admin/users/search?role=RESIDENT&keyword=${encodeURIComponent(keyword)}`)
            .then(response => {
                if (!response.ok) {
                    throw new Error('网络响应不正常');
                }
                return response.json();
            })
            .then(result => {
                if (result.code !== 200) {
                    throw new Error(result.message || '搜索失败');
                }
                
                const data = result.data;
                const tbody = document.getElementById('residentsList');
                tbody.innerHTML = '';
                
                if (!Array.isArray(data)) {
                    console.error('返回数据格式不正确:', data);
                    throw new Error('数据格式不正确');
                }
                
                if (data.length === 0) {
                    tbody.innerHTML = '<tr><td colspan="9" class="text-center">没有找到匹配的居民</td></tr>';
                    return;
                }
                
                data.forEach(resident => {
                    const tr = document.createElement('tr');
                    tr.innerHTML = `
                        <td>${resident.id}</td>
                        <td>${resident.username}</td>
                        <td>${resident.realName || '-'}</td>
                        <td>${resident.phone || '-'}</td>
                        <td>${resident.email || '-'}</td>
                        <td>${resident.address || '-'}</td>
                        <td>
                            <span class="badge ${resident.status === 1 ? 'bg-success' : 'bg-danger'}">
                                ${resident.status === 1 ? '正常' : '禁用'}
                            </span>
                        </td>
                        <td>${formatDate(resident.createTime)}</td>
                        <td>
                            <button class="btn btn-sm btn-info" onclick="editResident(${resident.id})">
                                编辑
                            </button>
                            <button class="btn btn-sm ${resident.status === 1 ? 'btn-warning' : 'btn-success'}"
                                    onclick="toggleStatus(${resident.id}, ${resident.status})">
                                ${resident.status === 1 ? '禁用' : '启用'}
                            </button>
                            <button class="btn btn-sm btn-danger" onclick="deleteResident(${resident.id})">
                                删除
                            </button>
                        </td>
                    `;
                    tbody.appendChild(tr);
                });
            })
            .catch(error => {
                console.error('搜索居民失败:', error);
                const tbody = document.getElementById('residentsList');
                tbody.innerHTML = '<tr><td colspan="9" class="text-center text-danger">搜索失败，请重试</td></tr>';
            });
    }

    // 格式化日期
    function formatDate(dateString) {
        if (!dateString) return '-';
        const date = new Date(dateString);
        return date.toLocaleString('zh-CN', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit'
        });
    }
    </script>
</th:block>
</body>
</html> 